package com.talkweb.ncfw.web.action;

import java.io.File;
import java.io.OutputStream;
import java.util.List;

import org.apache.log4j.Logger;

import com.talkweb.ncfw.component.Constants;
import com.talkweb.ncfw.component.commonfile.entity.FileBean;
import com.talkweb.ncfw.component.commonfile.service.ICommonFileService;
import com.talkweb.ncfw.data.IDataMap;
import com.talkweb.ncfw.data.Page;
import com.talkweb.ncfw.data.ProcessResult;
import com.talkweb.ncfw.exceptions.BizBaseException;
import com.talkweb.ncfw.exceptions.ViewBaseException;
import com.talkweb.ncfw.utils.PropertiesUtils;
import com.talkweb.ncfw.utils.StringUtils;
import com.talkweb.ncfw.web.struts2.BaseAction;
import com.talkweb.ncfw.web.utils.HttpServletUtils;

/**
 * <p>文件名称: CommonFileAction.java</p>
 * <p>文件描述: 公共文件上传Action</p>
 * <p>版权所有: 版权所有(C)2010</p>
 * <p>内容摘要: 简要描述本文件的内容，包括主要模块、函数及能的说明</p>
 * <p>其他说明: 其它内容的说明</p>
 * <p>完成日期: 2010-12-30</p>
 * <p>修改记录1:</p>
 * <pre>
 *    修改日期:
 *    修 改 人:
 *    修改内容:
 * </pre>
 * <p>修改记录2：…</p>
 * @author  Wuqingming
 */
public class CommonFileAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private ICommonFileService commonFileService;
	private File[] uploadFile;					//上传的文件
	private String[] uploadFileFileName;		//上传的文件名称
	private double fileLimitSize = StringUtils.isEmpty(PropertiesUtils.getProperty("commonfile.file.fileSizeMaxLimit"))
		? 2048 : Double.parseDouble(PropertiesUtils.getProperty("commonfile.file.fileSizeMaxLimit"));	//文件上传大小限制-默认为2M
	private static Logger logger = Logger.getLogger(CommonFileAction.class);
	
	public ICommonFileService getCommonFileService() {
		return commonFileService;
	}

	public void setCommonFileService(ICommonFileService commonFileService) {
		this.commonFileService = commonFileService;
	}

	public File[] getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File[] uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String[] getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String[] uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public double getFileLimitSize() {
		return fileLimitSize;
	}

	public void setFileLimitSize(double fileLimitSize) {
		this.fileLimitSize = fileLimitSize;
	}

	private ProcessResult checkFileSize () {
		ProcessResult resultBean = null;
		String fileSizeMaxLimit	= PropertiesUtils.getProperty("commonfile.file.fileSizeMaxLimit");
		if (StringUtils.isEmpty(fileSizeMaxLimit)) {
			resultBean = new ProcessResult(true, "验证通过.");
			return resultBean;
		}
		double systemFileSizeMaxLimit = Double.parseDouble(fileSizeMaxLimit);
		if (fileLimitSize > systemFileSizeMaxLimit) {
			resultBean = new ProcessResult(false, "上传设置的文件大小不能超过" + systemFileSizeMaxLimit + "kb");
			return resultBean;
		}
		int cursor = 0;
		for (File file : this.uploadFile) {
			double fileSize = file.length() / 1024.0;
			if (fileSize > this.fileLimitSize) {//最大允许上传10M的文件
				resultBean = new ProcessResult(false, "文件'" + this.uploadFileFileName[cursor] + "'大小不能超过" + this.fileLimitSize + "kb");
				return resultBean;
			}
			cursor++;
		}
		resultBean = new ProcessResult(true, "验证通过.");
		return resultBean;
	}
	
	/**
	 * 
	 * @author：Wuqingming 	        
	 * @date：2011-7-7
	 * @Description：文件上传
	 * @return
	 * @throws ViewBaseException
	 */
	public String uploadFile () throws ViewBaseException {
		ProcessResult resultBean 	= this.checkFileSize();
		if (!resultBean.isSuccess()) {
			HttpServletUtils.outJsonWhenUpload(this.getResponse(), resultBean);
		}
		String relationId				= this.getParameter("relationId");		//相关的业务ID
		StringBuffer resultBuffer 		= new StringBuffer("{success: true, fileArray: [");
		FileBean[] fileBeans			= null;
		try {
			fileBeans					= this.commonFileService.addFile(this.uploadFile, this.uploadFileFileName, true, null, null, relationId);
		} catch (BizBaseException e) {
			throw new ViewBaseException("文件上传失败, 失败详情: " + e.getMessage());
		}
		for (int i = 0; i < fileBeans.length; i++) {
			if (i >= 1) {
				resultBuffer.append(",");
			}
			resultBuffer.append("{fileId	: '").append(fileBeans[i].getFileId()).append("',");
			resultBuffer.append("fileName	: '").append(fileBeans[i].getFileName()).append("',");
			resultBuffer.append("filePath	: '").append(fileBeans[i].getFilePath()).append("',");
			resultBuffer.append("fileAbPath	: '").append(fileBeans[i].getAbsolutePath()).append("',");
			resultBuffer.append("fileOldName: '").append(fileBeans[i].getFileOldName()).append("',");
			resultBuffer.append("fileSize	: ").append(fileBeans[i].getFileSize()).append("}");
		}
		resultBuffer.append("]}");
		HttpServletUtils.outJsonWhenUpload(this.getResponse(), resultBuffer.toString());
		return null;
	}
	
	/**
	 * 
	 * @author：Wuqingming 	        
	 * @date：2011-7-7
	 * @Description：文件下载
	 * @return
	 */
	public String downloadFile () {
		try {
		    this.getResponse().setContentType("application/octet-stream");
		    OutputStream out 	= this.getResponse().getOutputStream();
		    String fileId 		= this.getRequest().getParameter("fileId");			//文件ID
		    String filePath 	= this.getRequest().getParameter("filePath");		//文件相对路径
		   // String fileName 	= this.getRequest().getParameter("fileName");		//下载文件名
		    FileBean fileBean	= null;
		    if (StringUtils.isNotEmpty(fileId)) {
		    	fileBean		= this.commonFileService.downloadFileById(fileId, this.getResponse());
		    } else if (StringUtils.isNotEmpty(filePath)) {
		    	fileBean		= this.commonFileService.downloadFile(filePath, this.getResponse());
		    }
		    if (fileBean == null) {
		    	return null;
		    }/*
		    if (StringUtils.isEmpty(fileName)) {
		    	fileName		= StringUtils.isNotEmpty(fileBean.getFileOldName()) ? 
		    			fileBean.getFileOldName() : fileBean.getFileName();
		    }
		    this.getResponse().addHeader("Content-Disposition", "attachment;filename=" + 
		    		new String((fileName).getBytes(System.getProperty("file.encoding")), "ISO-8859-1"));*/
		    try {
		        out.flush();
		    } catch (Exception e) {
		    	logger.error("文件下载异常.", e);
		    } finally {
		        if ( out != null ) {
		        	out.close();
		        	out = null;
		        }
		        if (fileBean != null && fileBean.getFile() != null) { 
		        	//文件保存模式为数据库或文件服务器
			        if (StringUtils.equals(fileBean.getSaveMode(), Constants.CommonFileConst.FILE_SAVE_MODE_DATABASE)
			        		|| StringUtils.equals(fileBean.getSaveMode(), Constants.CommonFileConst.FILE_SAVE_MODE_FSERVER)) {
			        	if (fileBean.getFile().exists()) {
			        		fileBean.getFile().delete();		//删除临时文件
			        	}
			        }
		        }
		    }
		    return null;
		} catch(Exception e) {
			logger.error(e);
		    return null;
		}
	}
	
	/**
	 * 
	 * @author：Wuqingming 	        
	 * @date：2011-8-7
	 * @Description：查询文件信息
	 * @return
	 */
	public String findFile () throws ViewBaseException {
		IDataMap<String, Object> condition = this.getParameterMap();
		String filePaths 			= this.getParameter("filePaths");
		String absolutePaths 		= this.getParameter("absolutePaths");
		if (StringUtils.isNotEmpty(filePaths)) {
			condition.put("filePathArray", filePaths.split(";"));
		}
		if (StringUtils.isNotEmpty(absolutePaths)) {
			condition.put("absolutePathArray", absolutePaths.split(";"));
		}
		Page<FileBean> page = new Page<FileBean>();
		page.setIfPage(false);
		try {
			page = this.getCommonFileService().findFile(page, condition);
		} catch (BizBaseException e) {
			throw new ViewBaseException(e.getMessage(), e);
		}
		List<FileBean> fileBeanList = page.getResult();
		HttpServletUtils.outJsonArray(this.getResponse(), fileBeanList.toArray());
		return null;
	}

}

